$psake.use_exit_on_error = $true
properties {
	$baseDir = resolve-path .
	$configuration = "debug"
	$filesDir = "$baseDir\BuildFiles"
	$version = git describe --abbrev=0 --tags
	if($version) {
		$version = $version + '.' + (git log $($version + '..') --pretty=oneline | measure-object).Count
	}
	else {
		$version = "1.0.0"
	}
	$nugetDir = "$baseDir\.NuGet"
	$sln = Get-Item -path $baseDir/*.sln
	$slnName  = ($sln.Name).Substring(0, $sln.Name.Length-4)
}

task Debug -depends Default
task Default -depends Package
#tc
task Clean-Solution -depends Clean-BuildFiles {
	. './vsvars2010.ps1'
    exec { msbuild $sln /t:Clean /v:quiet }
}	

task Update-AssemblyInfoFiles {
	$v = git describe --abbrev=0 --tags
	$commit = git log -1 $($v + '..') --pretty=format:%H
	Update-AssemblyInfoFiles $version $commit
}

task Build-Solution -depends Clean-Solution{
    exec { msbuild $sln /maxcpucount /t:Build /v:Minimal /p:Configuration=$configuration }
}

task Clean-BuildFiles {
    clean $filesDir
	create $filesDir
	create $filesDir\vsix
}

task Push-Nuget -depends Build-Nuget {
	$pkg = Get-Item -path $filesDir/vsix/packages/*.nupkg
	exec { .$nugetDir\nuget.exe push $filesDir\vsix\packages\$($pkg.Name) }
}

task Package -depends Build-Vsix {
  if( Test-Path $baseDir\$slnName\Readme.txt) {Copy-Item $baseDir\$slnName\Readme.txt $filesDir}
  if( Test-Path $baseDir\License.txt) {Copy-Item $baseDir\License.txt $filesDir}
  Copy-Item $baseDir\$slnName\bin\$configuration\* $filesDir
  cd $filesDir
  Copy-Item vsix\*.vsix .
  Copy-Item vsix\packages\AutoWrockTestable.*.nupkg $baseDir
  clean vsix
  exec { & $baseDir\Tools\zip.exe -9 -r $slnName-$version.zip . }
  cd $baseDir
  move-item *.nupkg $filesDir
}

task Build-Template -depends Build-Nuget {
  create $filesDir\vsix\ItemTemplates\Code
  cd $filesDir\vsix\ItemTemplates\Code
  Copy-Item $baseDir\bird.png .
  Copy-Item $baseDir\$slnName.Template\MyClassFacts.cs .
  $Spec = [xml](get-content "$baseDir\$slnName.Template\MyClassFacts.vstemplate")
  $Spec.VSTemplate.WizardData.packages.package[0].version = "$version"
  $Spec.Save("$filesDir\vsix\ItemTemplates\Code\MyClassFacts.vstemplate")
  exec { & $baseDir\Tools\zip.exe -9 -r myclassfacts.zip . }
  Remove-Item MyClassFacts.cs -Force
  Remove-Item MyClassFacts.vstemplate -Force
  Remove-Item bird.png -Force
  cd $baseDir
}

task Build-Nuget -depends Build-Solution {
  create $filesDir\vsix\packages
  exec { .$nugetDir\nuget.exe pack $baseDir\$slnName\$slnName.csproj -o $filesDir\vsix\Packages -version $version -prop Configuration=$configuration}
}

task Build-Vsix -depends Build-Template {
  cd $filesDir\vsix
  Copy-Item $baseDir\bird.png .
  Copy-Item -LiteralPath "$baseDir\$slnName.Template\[content_Types].xml" .
  Copy-Item $baseDir\License.txt .
  Copy-Item $baseDir\$slnName.Template\bin\$configuration\$slnName.Template.dll .
  Copy-Item $baseDir\$slnName.Template\bin\$configuration\$slnName.Template.pdb .
  Copy-Item  $baseDir\$slnName.Menu\bin\$configuration\$slnName.Menu.pkgdef .
  Copy-Item  $baseDir\$slnName.Menu\bin\$configuration\$slnName.Menu.dll .
  Copy-Item  $baseDir\$slnName.Menu\bin\$configuration\$slnName.Menu.pdb .
  $nugetFile = (Get-Item packages\*.nupkg)
  $nugetFile = $nugetFile.Name
  $Spec = [xml](get-content "$baseDir\$slnName.Template\extension.vsixmanifest")
  $Spec.Vsix.Content.CustomExtension[0].Type = "$nugetFile"
  $Spec.Vsix.Content.CustomExtension[0].Set_InnerXML("packages/$nugetFile")
  $Spec.Save("$filesDir\vsix\extension.vsixmanifest")
  Copy-Item $baseDir\packages\moq.*\*.nupkg packages
  Copy-Item $baseDir\packages\structuremap.*\*.nupkg packages
  create "$env:localappdata\Microsoft\VisualStudio\10.0Exp\Extensions\Matt Wrock\AutoWrockTestable"
  copy-item * "$env:localappdata\Microsoft\VisualStudio\10.0Exp\Extensions\Matt Wrock\AutoWrockTestable" -Recurse -Force
  exec { & $baseDir\Tools\zip.exe -9 -r "$slnName.vsix" "." }
  cd $baseDir
}

function clean($path) {
    remove-item -force -recurse $path -ErrorAction SilentlyContinue
}

function create([string[]]$paths) {
    foreach ($path in $paths) {
        if ((test-path $path) -eq $FALSE) {
            new-item -path $path -type directory | out-null
        }
    }
}

# Borrowed from Luis Rocha's Blog (http://www.luisrocha.net/2009/11/setting-assembly-version-with-windows.html)
function Update-AssemblyInfoFiles ([string] $version, [string] $commit) {
    $assemblyVersionPattern = 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)'
    $fileVersionPattern = 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)'
    $fileCommitPattern = 'AssemblyTrademarkAttribute\("([a-f0-9]{40})?"\)'
    $assemblyVersion = 'AssemblyVersion("' + $version + '")';
    $fileVersion = 'AssemblyFileVersion("' + $version + '")';
    $commitVersion = 'AssemblyTrademarkAttribute("' + $commit + '")';

    Get-ChildItem -path $baseDir -r -filter GlobalAssemblyInfo.cs | ForEach-Object {
        $filename = $_.Directory.ToString() + '\' + $_.Name
        $filename + ' -> ' + $version
        
        # If you are using a source control that requires to check-out files before 
        # modifying them, make sure to check-out the file here.
        # For example, TFS will require the following command:
        # tf checkout $filename
    
        (Get-Content $filename) | ForEach-Object {
            % {$_ -replace $assemblyVersionPattern, $assemblyVersion } |
            % {$_ -replace $fileVersionPattern, $fileVersion } |
			% {$_ -replace $fileCommitPattern, $commitVersion }
        } | Set-Content $filename
    }
}